/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.trick.admin.controller;

import it.trick.admin.App;
import it.trick.admin.binding.ChannelManageProgressBinding;
import it.trick.admin.model.ContentsBaseModel;
import it.trick.admin.model.ChannelModel;
import it.trick.admin.model.ChapterModel;
import it.trick.admin.model.PageModel;
import it.trick.admin.task.AddCategoryTask;
import it.trick.admin.task.AddChapterTask;
import it.trick.admin.task.AddPageTask;
import it.trick.admin.task.AddPreTask;
import it.trick.admin.task.ChangeChapterNameTask;
import it.trick.admin.task.ChangeContentsIndexTask;
import it.trick.admin.task.ChangePageNameTask;
import it.trick.admin.task.DeleteCategoryTask;
import it.trick.admin.task.DeleteChapterTask;
import it.trick.admin.task.DeletePageTask;
import it.trick.admin.task.DeletePreTask;
import it.trick.admin.task.GetChapterModelTask;
import it.trick.admin.task.GetPageModelTask;
import it.trick.admin.task.LoadCategoryTreeTask;
import it.trick.admin.task.LoadPageListTask;
import it.trick.admin.task.LoadPreListTask;
import it.trick.admin.task.PublicChapterTask;
import it.trick.admin.task.PublicPageTask;
import it.trick.admin.task.PublicPreTask;
import it.trick.admin.task.UpdateCategoryTask;
import it.trick.admin.task.UpdateChapterTask;
import it.trick.admin.task.UpdatePageTask;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

/**
 * FXML Controller class
 *
 * @author takahara
 */
public class ChannelTopController extends AnchorPane implements Initializable {

    private static ChannelTopController instance;
    // -----------------------------画面項目-------------------------------------
    @FXML
    public Button channelMenuButton;
    @FXML
    public VBox mainVBox;
    @FXML
    public TreeView<ContentsBaseModel> categoryTreeView;
    @FXML
    public ListView<PageModel> pageListView;
    @FXML
    public HBox progressIndicatorHBox;
    // -----------------------------タスク---------------------------------------
    public LoadCategoryTreeTask loadCategoryTreeTask = new LoadCategoryTreeTask();
    public LoadPageListTask loadPageListTask = new LoadPageListTask();
    public LoadPreListTask loadPreListTask = new LoadPreListTask();
    public ChangeContentsIndexTask changeIndexTask = new ChangeContentsIndexTask();
    public AddCategoryTask addCategoryTask = new AddCategoryTask();
    public AddChapterTask addChapterTask = new AddChapterTask();
    public AddPageTask addPageTask = new AddPageTask();
    public AddPreTask addPreTask = new AddPreTask();
    public DeleteCategoryTask deleteCategoryTask = new DeleteCategoryTask();
    public DeleteChapterTask deleteChapterTask = new DeleteChapterTask();
    public DeletePageTask deletePageTask = new DeletePageTask();
    public DeletePreTask deletePreTask = new DeletePreTask();
    public UpdateCategoryTask updateCategoryTask = new UpdateCategoryTask();
    public UpdateChapterTask updateChapterTask = new UpdateChapterTask();
    public UpdatePageTask updatePageTask = new UpdatePageTask();
    public GetChapterModelTask getChapterModelTask = new GetChapterModelTask();
    public GetPageModelTask getPageModelTask = new GetPageModelTask();
    public PublicChapterTask publicChapterTask = new PublicChapterTask();
    public PublicPageTask publicPageTask = new PublicPageTask();
    public PublicPreTask publicPreTask = new PublicPreTask();
    public ChangeChapterNameTask changeChapterNameTask = new ChangeChapterNameTask();
    public ChangePageNameTask changePageNameTask = new ChangePageNameTask();
    // -----------------------------その他---------------------------------------
    public ChannelModel channelModel;

    /**
     * コンストラクタ
     */
    public ChannelTopController() {
        this.initFxml();
    }

    /**
     * FXMLの初期化
     */
    private void initFxml() {
        try {

            // ---------------------------------------------------
            // FXMLのロードと設定
            // ---------------------------------------------------
            FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("resource/fxml/channel_manage.fxml"));
            fxmlLoader.setRoot(this);
            // 自分自身をコントロールとして設定
            fxmlLoader.setController(this);

            fxmlLoader.load();
        } catch (IOException exception) {
            App.getInstance().showErrorPop(exception);
        }

        instance = this;
    }

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
    }

    /**
     * セットアップ
     */
    public void setup(ChannelModel channelModel) {
        this.channelModel = channelModel;
        initCategoryTree();
        initPageList();

        // プログレスの初期化
        progressIndicatorHBox.visibleProperty().bind(
                new ChannelManageProgressBinding(
                loadCategoryTreeTask,
                loadPageListTask,
                loadPreListTask,
                changeIndexTask,
                addCategoryTask,
                addChapterTask,
                addPageTask,
                addPreTask,
                deleteCategoryTask,
                deleteChapterTask,
                deletePageTask,
                deletePreTask,
                updateCategoryTask,
                updateChapterTask,
                updatePageTask,
                getChapterModelTask,
                getPageModelTask,
                publicChapterTask,
                publicPageTask,
                publicPreTask,
                changeChapterNameTask,
                changePageNameTask));

        loadCategoryTreeTask.setup(channelModel);
        loadCategoryTreeTask.restart();
    }

    /**
     * カテゴリツリー初期化
     */
    private void initCategoryTree() {

        // ---------------------------------------------------------------------
        // サービスの正常処理イベント
        // ---------------------------------------------------------------------
        loadCategoryTreeTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {

                // サービスの処理結果を受け取る
                TreeItem<ContentsBaseModel> treeItemRoot = (TreeItem<ContentsBaseModel>) t.getSource().getValue();

                // Tree Root Nodeを設定する
                categoryTreeView.setRoot(treeItemRoot);
                treeItemRoot.setExpanded(true);
            }
        });

        // ---------------------------------------------------------------------
        // サービスの例外イベント
        // ---------------------------------------------------------------------
        loadCategoryTreeTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                Exception ex = (Exception) loadCategoryTreeTask.getException();
                App.getInstance().showErrorPop(ex);
            }
        });

        categoryTreeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue ov, Object oldValue, Object newValue) {

                if (newValue != null) {

                    // 以下はChapterにのみ有効
                    if (categoryTreeView.getSelectionModel().getSelectedItem().getValue() instanceof ChapterModel) {

                        ChapterModel chapterModel = ((TreeItem<ChapterModel>) newValue).getValue();
                        loadPageListTask.setup(chapterModel);
                        loadPageListTask.restart();
                    }
                }
            }
        });
    }

    /**
     * ページツリー初期化
     */
    private void initPageList() {

        // ---------------------------------------------------------------------
        // サービスの正常処理イベント
        // ---------------------------------------------------------------------
        loadPageListTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {

                // サービスの処理結果を受け取る
                List<PageModel> listItems = (List<PageModel>) t.getSource().getValue();

                // Tree Root Nodeを設定する
                pageListView.getItems().setAll(listItems);
            }
        });
    }

    /**
     * チャンネル選択
     */
    @FXML
    public void changeChannelMenuAction() {
        SelectChannelController controller = new SelectChannelController();
        App.getInstance().showPopStage(controller, "チャンネル選択", 500, 500, false);
    }

    /**
     * チャンネル設定
     */
    @FXML
    public void changeSettingMenuAction() {
        if (App.getInstance().getSite() != null && channelModel != null) {
            SettingChannelController controller = new SettingChannelController(channelModel);
            App.getInstance().showPopStage(controller, "チャンネル設定", 500, 500, false);
        }
    }

    /**
     * 更新
     */
    @FXML
    public void updateAction() {
        categoryTreeView.getSelectionModel().clearSelection();
        if (categoryTreeView.getRoot() != null) {
            categoryTreeView.getRoot().getChildren().clear();
        }

        pageListView.getItems().clear();

        Label label = new Label("コンテンツの指定がありません。");
        mainVBox.getChildren().setAll(label);

        loadCategoryTreeTask.setup(channelModel);
        loadCategoryTreeTask.restart();
    }

    /**
     * Get App Instance
     *
     * @return
     */
    public static ChannelTopController getInstance() {
        return instance;
    }
}
